$package('common.tools.email');
if(isRequestHave){
	$import('itsm.request.requestEmailHistory');
}
$import("common.config.category.eventCategoryTree");
$import("common.security.userUtil");
if(isCIHave){
	$import("itsm.cim.configureItemUtil");
}
$import("common.config.dictionary.dataDictionaryUtil");
$import('itsm.itsop.selectCompany');
$import('common.security.xssUtil');
$import('common.config.includes.includes');
/**  
 * @author QXY  
 * @constructor email
 * @description tools/email.jsp
 * @date 2010-11-17
 */
common.tools.email.email=function() 
{
	this.replyState = false;	// 弹出窗口的状态. true为回复窗口，false为新邮件窗口
	this._emailFlag = true;
	var refreshMessage;
	return {
		
		/**
		 * @description 邮箱后缀格式化.
		 */
		sinaFrm:function(cellvalue, options){
			var cellvalue1=cellvalue.replace('.sina','')
			return cellvalue;
		},
		/**
		 * @description 格式化.
		 */
		contentUnFormatter:function ( cellvalue, options){
			   return cellvalue;
			},
		/**
		 * @description 类型格式化.
		 */
		folderNameFormat:function(cellvalue, options){
			if(cellvalue=="INBOX"){
				return i18n['common_receive'];
			}
			else{
				return i18n['common_sent'];
			}
		},
		 /**
         * @description 标题格式化
         */
        emailGridTitleFormatter: function (cell, opt, data) {
            return "<a onclick=javascript:itsm.request.requestEmailHistory.showEmailDetail('"+data.emailMessageId+"') >" + cell + "</a>";
        },
		
        /**
         * @description 标题格式化
         */
        isToRequestFormatter: function (cell, opt, data) {
        	if(cell)
        		return "<span style='color:red'>"+i18n['label_basicConfig_deafultCurrencyYes']+"</span>";
        	else
        		return i18n['label_basicConfig_deafultCurrencyNo'];
        },
        
        /**
         * @description 发件人格式化
         */
        FromUserFormatter:function(cellvalue,options){
        	if(cellvalue!=null && cellvalue!=''){
        		return cellvalue.replace(/</g,' ').replace(/>/g,' ');
        	}else
        		return '';
        },
        /**
         * @description 收件人格式化
         */
        ToUserFormatter:function(cellvalue,options){
        	if(cellvalue!=null && cellvalue!=''){        		
        		return cellvalue.replace(/</g,' ').replace(/>/g,' ');
        	}else
        		return '';
        },
        /**
         * @description 回复发件人格式化
         */
        FromUserByReplyFormatter:function(cellvalue){
        	var newCellValue=cellvalue.substring(cellvalue.lastIndexOf("(")+1,cellvalue.lastIndexOf(")"));
        	return newCellValue;
        },
		/**
		 * @description 加载邮件列表.
		 */
		showEmailGrid:function(){
			
			var params = $.extend({},jqGridParams, {
				url:'email!findEmail.action',
				colNames:[i18n['number'],i18n['title_mailTitle'],'',i18n['title_mailType'],i18n['title_mailFromUser'],'',i18n['title_mailToUser'],i18n['title_sendTime'],i18n['title_receviceTime'],i18n['isToRequest']],
				colModel:[
			   		{name:'emailMessageId',width:60,sortable:true},
			   		{name:'subject',width:200,formatter:this.emailGridTitleFormatter},
			   		{name:'subject',width:150,hidden:true},
			   		{name:'folderName',width:50,formatter:this.folderNameFormat,align:'center'},
			   		{name:'fromUser',width:200,formatter:this.FromUserFormatter},
			   		{name:'fromUser',hidden:true},
			   		{name:'toUser',width:200,formatter:this.ToUserFormatter,sortable:false},
			   		{name:'sendDate',width:120,formatter:timeFormatter,align:'center'},
			   		{name:'receiveDate',width:120,formatter:timeFormatter,align:'center'},
			   		{name:'isToRequest',width:120,formatter:this.isToRequestFormatter,align:'center'}
			   	],
				toolbar: [true,"top"],	
				jsonReader: $.extend(jqGridJsonReader, {id: "emailMessageId"}),
				sortname:'emailMessageId',
				sortorder:'desc',
				ondblClickRow:function(rowId){itsm.request.requestEmailHistory.showEmailDetail(rowId)},
				pager:'#emailPager'
			});
			$("#emailGrid").jqGrid(params);
			$("#emailGrid").navGrid('#emailPager',navGridParams);
			//列表操作项
			$("#t_emailGrid").css(jqGridTopStyles);
			$("#t_emailGrid").append($('#emailGridToolbar').html());
			//自适应大小
			setGridWidth("#emailGrid","regCenter",20);
			
		},
		/**
		 * @description 清理值.
		 */
		clearElement:function(){
				$('#addEmail [name="emailDto.receiveAddress"]').val("");
				$('#addEmail [name="emailDto.subject"]').val("");
				$('#addEmail [name="emailDto.remarks"]').val("");
				$('#addEmail [name="emailDto.description"]').val("");
				$('#addEmail [name="affachment"]').val("");
				$('#addEmail [name="emailDto.affachmentPath"]').val("");
		},
		
		/**
		 * @description 引用原文.
		 */
		appendOldSubject:function(){
			var tb = $('#addEmail > form > table');
			$('<tr class="temp"><td colspan="2"><div id = "separatorLine" style="border-bottom:#CCC 1px dashed; margin-top:10px; margin-bottom:10px"></div></td></tr>').prependTo(tb);
			$('<tr class="temp"><td>'+i18n['title_sendTime']+'</td><td><div id="oldSentDate"  style="width:100%" ></div></td></tr>').prependTo(tb);
			$('<tr class="temp"><td>'+i18n['details']+'</td><td><div id="oldContents" style="width:100%"></div></td></tr>').prependTo(tb);
			$('<tr class="temp"><td>'+i18n['title']+'</td><td><div id="oldSubject"></div></td></tr>').prependTo(tb);
			$('<tr class="temp"><td width="100px">发件箱</td><td><div id="oldFrom"></div></td></tr>').prependTo(tb);
			replyState = true;
		},
		/**
		 * @description 删除
		 */
		removeOldSubject:function(){
			$('.temp').remove();
			replyState = false;
		},
		
		/**
		 * @description 创建邮件.
		 */
		toolbar_addEmail:function(){
			
			common.tools.email.email.clearElement();
			if (replyState){
				common.tools.email.email.removeOldSubject();
			}
			windows('addEmail',{title:i18n["tool_mail_addEmail"],width:650});
			common.tools.email.email.add_email_openwindow();
			
			var oEditor = CKEDITOR.instances.emailContent;
			oEditor.setData('');

		},
		
		/**
		 * @description 回复邮件.
		 */
		toolbar_replyEmail:function(){
			
			checkBeforeMethod("#emailGrid",function(rowIds){
				var _emailAddr='';
				var subData=$('#emailGrid').getRowData(rowIds[0]);
				$.each(rowIds,function(k,v){
					var rowData=$('#emailGrid').getRowData(v);
					var fromUserAddress = rowData.fromUser;
					fromUserAddress = fromUserAddress.substring(fromUserAddress.indexOf('<')+1,fromUserAddress.indexOf('>'));
					if(_emailAddr.indexOf(fromUserAddress)==-1){//避免重复
						if(_emailAddr==''){
							_emailAddr=fromUserAddress;
						}else{
							_emailAddr+=';'+fromUserAddress;
						}
					}
				})
				$.extend(subData,{'fromUser':_emailAddr});	
				common.tools.email.email.toolbar_replyEmailMethod(subData);
			});
		},
		/**
		 * @description 回复邮件方法
		 **/
		toolbar_replyEmailMethod:function(rowData){
			initCkeditor('replayemailContent','NoImage',function(){});
			if(!replyState){
				common.tools.email.email.appendOldSubject();
			}
			var _oldFrom=rowData.fromUser;
			if(_oldFrom.indexOf('[')>=0){
				
				_oldFrom=_oldFrom.substring(0,_oldFrom.indexOf('['));
			}
			windows_beforeClose('replayEmail',{width:650,title:i18n["label_replay"]},function(){
				var instance = CKEDITOR.instances['replayemailContent'];
			    if(instance)
			    {
			        CKEDITOR.remove(instance);
			        $('#cke_replayemailContent').remove();
			    }
			});
			$("#receivereplayress_to").val(trim(_oldFrom));
			$("#replaysubject").val(i18n["label_im_reply"]+":"+rowData.subject);
			var oEditor = CKEDITOR.instances.replayemailContent;
			oEditor.setData('');
		},
		
		/**
		 * @description打开新增邮件窗口.
		 **/
		add_email_openwindow:function(){
			initCkeditor('emailContent','NoImage',function(){});
			windows_beforeClose('addEmail',{width:650},function(){
				var instance = CKEDITOR.instances['emailContent'];
			    if(instance)
			    {
			        CKEDITOR.remove(instance);
			        $('#cke_emailContent').remove();
			    }
			});
		},
		
		/**
		 * @description 关闭新增邮件窗口.
		 **/
		add_closewindow:function(){
			$('#addEmail').dialog('close');
		},
		
		/**
		 * @description add Eamil
		 */
		add_email:function(){
			if($('#addEmail form').form('validate')){
				if(checkEmail($('#receiveAddress_to').val())){//邮件验证是否正确
					var oEditor = CKEDITOR.instances.emailContent;
					var edesc=trim(oEditor.getData());
					$('#emailContent').val(edesc);
					$('#subject').val(common.security.xssUtil.html_encode($('#subject').val()));
					var _param = $('#addEmail form').serialize();
					_param = _param + '&emailDto.affachment='+ $("#affachment").val();
					startProcess();
					$.post('email!testEmail.action','isSend=true', function(data){
						if(data){
							var _url='email!toEmail.action';
							$.post(_url,_param,function(result){
								endProcess();
								if(result){
									$('#addEmail').dialog('close');
									resetForm("#addEmailForm");
									msgShow(i18n['msg_sendSuccessful'],'show');
									$('#emailGrid').trigger('reloadGrid');
								}else{
									msgShow(i18n['ERROR_EMAIL_ACCOUNT_ERROR'],'show');
								}
							});
						}else{endProcess();
							msgShow(i18n['ERROR_EMAIL_ACCOUNT_ERROR'],'show');
						}
					});
				}else{
					msgAlert(i18n['emailFormatError'],'info');
					
				}
			}
		},
		/**
		 * @description add Eamil
		 */
		replay_email:function(){
			if($('#replayEmail form').form('validate')){
				if(checkEmail($('#receivereplayress_to').val())){//邮件验证是否正确
					var oEditor = CKEDITOR.instances.replayemailContent;
					var edesc=trim(oEditor.getData());
					$('#replayemailContent').val(edesc);
					$('#replaysubject').val(common.security.xssUtil.html_encode($('#replaysubject').val()));
					var _param = $('#replayEmail form').serialize();
					_param = _param + '&emailDto.affachment='+ $("#affachment").val();
					startProcess();
					$.post('email!testEmail.action','isSend=true', function(data){
						if(data){
							var _url='email!toEmail.action';
							$.post(_url,_param,function(result){
								endProcess();
								if(result){
									$('#replayEmail').dialog('close');
									resetForm("#replayEmailForm");
									msgShow(i18n['msg_sendSuccessful'],'show');
									$('#emailGrid').trigger('reloadGrid');
								}else{
									msgShow(i18n['ERROR_EMAIL_ACCOUNT_ERROR'],'show');
								}
							});
						}else{endProcess();
							msgShow(i18n['ERROR_EMAIL_ACCOUNT_ERROR'],'show');
						}
					});
				}else{
					msgAlert(i18n['emailFormatError'],'info');
					
				}
			}
		},
		/**
		 * @description 选择请求者.
		 */
		selectRequestCreator:function(){
			common.security.userUtil.selectUser('#email_selectCreator','#email_addRequestUserId','','fullName',$('#email_toRequest_companyNo').val());
		},
		
		/**
		 * @description 邮件转请求获取邮件id
		 */
		emailToRequest_aff:function(){
			checkBeforeEditGrid('#emailGrid',common.tools.email.email.emailToRequest);
		},
		
		/**
		 * @description 转成可编辑请求
		 */
		emailToRequest:function(rowData){

			if(rowData.isToRequest!=i18n['label_basicConfig_deafultCurrencyNo']){
				msgAlert(i18n['alreadyToRequestSuccess'],'info');
			}else{
				//加载数据字典
				common.config.dictionary.dataDictionaryUtil.loadOptionsByCode('effectRange','#email_request_effectRange');
				common.config.dictionary.dataDictionaryUtil.loadOptionsByCode('seriousness','#email_request_seriousness');
				common.config.dictionary.dataDictionaryUtil.loadOptionsByCode('imode','#email_request_imode');
				common.config.dictionary.dataDictionaryUtil.loadOptionsByCode('level','#email_request_level');
				common.config.dictionary.dataDictionaryUtil.loadOptionsByCode('priority','#email_request_priority');

				//var _userName=rowData.fromUser.substring(rowData.fromUser.indexOf("[")+1, rowData.fromUser.indexOf("]"));
				var _userName=rowData.toUser;
				if(_userName!=null && _userName!=''){
					$.post('user!getUserDetailByLoginName.action?userName='+trim(_userName),function(data){
						if(data!=null && data.userId!=null && data.userId!=''){
							$('#email_selectCreator').val(_userName);
							$('#email_addRequestUserId').val(data.userId);
						}else{
							$('#email_selectCreator').val(fullName);
							$('#email_addRequestUserId').val(userId);
						}
					});
				}else{
					$('#email_selectCreator').val(fullName);
					$('#email_addRequestUserId').val(userId);
				}
				common.config.includes.includes.loadCategoryIncludesFile();//加载请求分类面板
				windows_beforeClose('logCall_win',{width:580},function(){
					var instance = CKEDITOR.instances['email_request_edesc'];
				    if(instance)
				    {
				        CKEDITOR.remove(instance);
				        $('#cke_email_request_edesc').remove();
				    }
				});
				$.post('email!findEmailMessageById.action','eid='+rowData.emailMessageId,function(data){
					if(data!=null){
						$("#email_emailMessageId").val(data.emailMessageId);
						$('#email_request_etitle').val(data.subject);
						initCkeditor('email_request_edesc','Simple',function(){
							var oEditor = CKEDITOR.instances.email_request_edesc;
//							$('#email_request_edesc').val(data.content);
							oEditor.setData(data.content);
						});
						if(data.affachment!=null){
							$('#email_request_attachmentAid').val('');
							var aids = '';
							for(var i=0;i<data.affachment.length;i++){
								aids +='&requestDTO.aids='+data.affachment[i].aid
//								$('#email_request_attachmentStr').val(
//										$('#email_request_attachmentStr').val()+
//										data.affachment[i].attachmentName+'=='+data.affachment[i].url+'-s-'
//								);
							}
							$('#email_request_attachmentAid').val(aids);
						}
						
					}
				})
			}
		},
		/**
		 * @description 邮件转请求
		 */
		emailToRequest_opt:function(){
			var title= $('#email_request_etitle').val();
			$('#email_request_etitle').val(trim(title));
			if($('#mailTrqForm').form('validate')){
				startProcess();
				$('#link_addcall_ok').attr('disabled','true');
				var oEditor = CKEDITOR.instances.email_request_edesc;
				var edesc=trim(oEditor.getData());
				$('#email_request_edesc').val(edesc);
				var email_request_edesc=edesc==''?false:true;
				if(!email_request_edesc){
					endProcess();
					msgAlert(i18n['titleAndContentCannotBeNull'],'info');
				}else{
					var frm = $('#logCall_win form').serialize()+$('#email_request_attachmentAid').val();
					var url = 'request!saveRequest.action';
					$.post(url,frm, function()
					{
						endProcess();
						$('#link_addcall_ok').removeAttr('disabled');	
						$('#logCall_win').dialog('close');
						$('#email_request_etitle').val('');
						$('#email_request_edesc').val('');
						$('#mailToRequestCategoryName').val('');
						$('#emailGrid').trigger('reloadGrid');
						msgShow(i18n['msg_addRequestSuccessful'],'show');
						
					});
				}
				
			}
		},
		/**
		 * @description 打开搜索窗口
		 */
		openEmailMessageSearchWin:function(){
			windows('emailMessageSearch_win',{width:450});
		},
		/**
		 * @description 搜索邮件
		 */
		emailMessageSearch:function(){
			if($('#emailMessageSearchForm').form('validate')){
				var _url = 'email!findEmail.action';	
				var sdata = $('#emailMessageSearch_win form').getForm();
				var postData = $("#emailGrid").jqGrid("getGridParam", "postData");     
				$.extend(postData, sdata);
				$('#emailGrid').jqGrid('setGridParam',{page:1,url:_url}).trigger('reloadGrid');
			}
		},
		/**
		 * @description 邮件的发送测试
		 */
		testEmailSend:function(){
			$.post('email!testEmail.action','isSend=true', function(data){
				if(data){
					msgShow('OK','show');
				}else{
					msgShow(i18n['ERROR_EMAIL_ACCOUNT_ERROR'],'show');
				}
			});
		},
		/**
		 * @description 判断是否选择要删除的邮件
		 */
		deleteEmailMessage_aff:function(){
			checkBeforeDeleteGrid('#emailGrid', this.deleteEmailMessageOpt);
		},
		/**
		 * @description 删除邮件操作
		 * @param rowsId
		 */
		deleteEmailMessageOpt:function(rowsId){
			var url="email!deleteEmailMessage.action";
			var param = $.param({'ids':rowsId},true);
			$.post(url, param, function()
			{
				$('#emailGrid').trigger('reloadGrid');
				msgShow(i18n['msg_deleteSuccessful'],'show');
				
			});	
		},
		/**
		 * @description 邮件扫描
		 */
		scanEmailServer:function(){
			//显示进程
			$('#email_scanemail_alert').text('['+i18n['label_email_scanAlert']+']');
			$('#email_scanemail_but').linkbutton({disabled:true});
			$.ajax({
				type:'post',
				url:'request!scanEmail.action',
				data:'',
				dataType:'json',
				success: function(data) {
					//scanEmailStatus();
					$('#email_scanemail_alert').text('['+i18n['msg_company_scansucess']+']');
					$('#email_scanemail_but').linkbutton({disabled:false});
					$('#emailGrid').trigger('reloadGrid');
				},
				error: function(data) {
					$('#email_scanemail_alert').text('['+i18n['ERROR_SCANEMAILMESSAGE']+']');
					$('#email_scanemail_but').linkbutton({disabled:false});
					return false;
				}
			});
			
		},
		/**
		 * @description 扫描邮箱
		 */
		scanEmailStatus:function(){
			$.post("activeMQ!findQueueStatus.action",{"queueName":"ScanEmailMessageQueue"},function(data){
				if(data){
					$('#email_scanemail_alert').text('');
					$('#email_scanemail_but').linkbutton({disabled:false});
					msgShow(i18n['msg_company_scansucess'],'show');
					window.clearInterval(refreshMessage);
				}else{
					if(_emailFlag){
					    refreshMessage=setInterval(function(){
					    	common.tools.email.email.scanEmailStatus();
						},1000);
					    _emailFlag = false;
					}
					
				}
				
			});
		},
		/**
		 * @description 初始化
		 */
		init:function(){
			//绑定日期控件
			DatePicker97(['#receiveStartDate','#receiveEndDate','#sendStartDate','#sendEndDate']);
			$("#email_loading").hide();
			$("#email_content").show();
			//加载发送邮件配置信息
			//common.tools.email.email.getSendEmailConfigure();
			common.tools.email.email.showEmailGrid();
			$('#email_selectCIName').click(function(){
				itsm.cim.configureItemUtil.findConfigureItemByLoginName('#email_selectCIName','#email_addRequestCIId',$('#email_selectCreator').val());
			});	
			
			$('#mailToRequestCategoryName').click(function(){
				common.config.category.eventCategoryTree.showSelectTree('#request_category_select_window'
						,'#request_category_select_tree'
						,'Request'
						,'#mailToRequestCategoryName'
						,'#mailToRequestCategoryNo');
				
			});
			$('#folderNameEmailSelect').text(i18n.common_sent);
			//选择公司
			$('#email_toRequest_companyName').click(function(){
				itsm.itsop.selectCompany.openSelectCompanyWin('#email_toRequest_companyNo','#email_toRequest_companyName','#email_toRequest_companyNo,#email_toRequest_companyName');
			});
			//加载默认公司
			common.security.defaultCompany.loadDefaultCompany('#email_toRequest_companyNo','#email_toRequest_companyName');
		}
	};
	
}();
$(document).ready(common.tools.email.email.init);

